package org.mixed.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.mixed.core.domain.ApiResponse;
import org.mixed.core.domain.Constants;
import org.mixed.core.domain.SysUser;
import org.mixed.core.enums.Authorization;
import org.mixed.core.exception.InvalidArgumentException;
import org.mixed.core.exception.LoginException;
import org.mixed.core.interceptor.AuthorizationInterceptor;
import org.mixed.core.resource.Info;
import org.mixed.core.resource.info.GroupInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

public class MixBaseController {
    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    boolean allowVisit(HttpServletRequest request, Authorization authorization) {
        if (authorization == null) {
            return true;
        }
        SysUser SysUser = (SysUser) request.getAttribute(Constants.ATTRIBUTE_MAGIC_USER);
        return authorizationInterceptor.allowVisit(SysUser, request, authorization);
    }

    boolean allowVisit(HttpServletRequest request, Authorization authorization, Info entity) {
        if (authorization == null) {
            return true;
        }
        SysUser sysUser = (SysUser) request.getAttribute(Constants.ATTRIBUTE_MAGIC_USER);
        return authorizationInterceptor.allowVisit(sysUser, request, authorization, entity);
    }

    boolean allowVisit(HttpServletRequest request, Authorization authorization, GroupInfo group) {
        if (authorization == null) {
            return true;
        }
        SysUser sysUser = (SysUser) request.getAttribute(Constants.ATTRIBUTE_MAGIC_USER);
        return authorizationInterceptor.allowVisit(sysUser, request, authorization, group);
    }

    @ExceptionHandler(LoginException.class)
    public ApiResponse<Void> invalidLogin(LoginException exception) {
        return ApiResponse.fail(401, exception.getMessage());
    }

    @ExceptionHandler(InvalidArgumentException.class)
    public ApiResponse<Void> invalidArgument(InvalidArgumentException exception) {
        return ApiResponse.fail(exception.getCode(), exception.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<Void> exceptionHandler(Exception exception) {
        return ApiResponse.fail(401, exception.getMessage());
    }
}
